package com.nnnu.wsnackshop.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.dto.OrderCreateDTO;
import com.nnnu.wsnackshop.pojo.dto.OrderPageQueryDTO;
import com.nnnu.wsnackshop.pojo.entity.Orders;
import com.nnnu.wsnackshop.pojo.vo.LogisticsTrackVO;
import com.nnnu.wsnackshop.pojo.vo.OrderPreviewVO;
import com.nnnu.wsnackshop.pojo.vo.OrderVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IOrdersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户端-订单 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("userOrdersController")
@RequestMapping("/api/user/orders")
@Tag(name = "用户端-订单接口")
@Slf4j
@RequiresRoles(value = { "user" }, logical = Logical.OR)
@RequiredArgsConstructor
public class OrdersController extends BaseController {

    private final IOrdersService ordersService;

    /**
     * 获取用户订单统计信息
     */
    @Operation(summary = "获取订单统计", description = "获取当前用户的订单统计信息")
    @GetMapping("/stats")
    public Result<Map<String, Object>> getOrderStats() {
        Integer userId = getUser().getId();
        log.info("[用户端] 获取用户订单统计 userId={}", userId);

        // 统计当前用户的订单总数
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, userId)
                .isNull(Orders::getDeleted);
        long total = ordersService.count(wrapper);

        // 统计不同状态的订单数量
        Map<String, Object> stats = new HashMap<>();
        stats.put("total", total);

        // 待付款订单
        wrapper.clear();
        wrapper.eq(Orders::getUserId, userId)
                .eq(Orders::getPayStatus, 0); // 0=pending
        stats.put("pending_payment", ordersService.count(wrapper));

        // 待发货订单
        wrapper.clear();
        wrapper.eq(Orders::getUserId, userId)
                .eq(Orders::getPayStatus, 1) // 1=paid
                .in(Orders::getOrderStatus, 0, 1); // 0=new, 1=accepted
        stats.put("pending_shipment", ordersService.count(wrapper));

        // 配送中/待收货订单
        wrapper.clear();
        wrapper.eq(Orders::getUserId, userId)
                .eq(Orders::getPayStatus, 1) // 1=paid
                .in(Orders::getOrderStatus, 2, 3); // 2=packing, 3=delivering
        stats.put("pending_receive", ordersService.count(wrapper));

        return Result.success(stats, MessageConstants.SELECT_OK);
    }

    /**
     * 订单预览（购物车）
     */
    @GetMapping("/preview/cart")
    public Result<OrderPreviewVO> previewOrderFromCart(@RequestParam String cartItemIds) {
        Integer userId = getUserId();
        OrderPreviewVO previewVO = ordersService.previewOrderFromCartItems(userId, cartItemIds);
        return Result.success(previewVO);
    }

    /**
     * 订单预览（直接购买）
     */
    @GetMapping("/preview/product")
    public Result<OrderPreviewVO> previewOrderFromProduct(
            @RequestParam Integer productId,
            @RequestParam Integer skuId,
            @RequestParam Integer quantity) {

        Integer userId = getUserId();
        OrderPreviewVO previewVO = ordersService.previewOrderFromProduct(userId, productId, skuId, quantity);
        return Result.success(previewVO);
    }

    /**
     * 创建订单
     */
    @PostMapping
    public Result<OrderVO> createOrder(@RequestBody OrderCreateDTO orderCreateDTO) {
        Integer userId = getUserId();
        OrderVO order = ordersService.createOrder(userId, orderCreateDTO);
        return Result.success(order);
    }

    /**
     * 获取订单列表
     */
    @GetMapping
    public Result<PageResult<OrderVO>> getOrders(OrderPageQueryDTO queryDTO) {
        Integer userId = getUserId();
        PageResult<OrderVO> pageResult = ordersService.getOrdersByUserId(userId, queryDTO);
        return Result.success(pageResult);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/{id}")
    public Result<OrderVO> getOrderDetail(@PathVariable Long id) {
        Integer userId = getUserId();
        OrderVO orderVO = ordersService.getOrderDetail(userId, id);
        return Result.success(orderVO);
    }

    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    public Result<Boolean> cancelOrder(
            @PathVariable Integer id,
            @RequestParam String reason) {

        Integer userId = getUserId();
        boolean success = ordersService.cancelOrder(userId, id, reason);
        return Result.success(success);
    }

    /**
     * 确认收货
     */
    @PostMapping("/{id}/complete")
    public Result<Boolean> completeOrder(@PathVariable Integer id) {
        Integer userId = getUserId();
        boolean success = ordersService.completeOrder(userId, id);
        return Result.success(success);
    }

    /**
     * 确认自提
     */
    @PostMapping("/{id}/self-pickup")
    public Result<Boolean> confirmSelfPickup(@PathVariable Integer id) {
        Integer userId = getUserId();
        boolean success = ordersService.confirmSelfPickup(userId, id.longValue());
        return Result.success(success);
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteOrder(@PathVariable Integer id) {
        Integer userId = getUserId();
        boolean success = ordersService.deleteOrder(userId, id);
        return Result.success(success);
    }

    /**
     * 支付订单
     */
    @PostMapping("/{id}/pay")
    public Result<Boolean> payOrder(
            @PathVariable Integer id,
            @RequestParam String paymentMethod) {

        Integer userId = getUserId();
        boolean success = ordersService.payOrder(userId, id, paymentMethod);
        return Result.success(success);
    }

    /**
     * 获取订单物流信息
     */
    @GetMapping("/{id}/logistics")
    public Result<LogisticsTrackVO> getOrderLogistics(@PathVariable Integer id) {
        Integer userId = getUserId();
        LogisticsTrackVO logisticsTrack = ordersService.getOrderLogistics(userId, id);
        return Result.success(logisticsTrack);
    }

    /**
     * 检查商品SKU库存
     */
    @GetMapping("/check-stock/{skuId}")
    public Result<Map<String, Object>> checkSkuStock(@PathVariable("skuId") Integer skuId) {
        Map<String, Object> result = ordersService.checkSkuStock(skuId);
        return Result.success(result);
    }

    /**
     * 再次购买
     * 将订单中的商品添加到购物车
     */
    @PostMapping("/{id}/buy-again")
    @Operation(summary = "再次购买", description = "将订单商品添加到购物车")
    public Result<Map<String, Object>> buyAgain(@PathVariable Long id) {
        log.info("再次购买: orderId={}", id);
        Integer userId = getUserId();

        int addedCount = ordersService.buyAgain(userId, id);

        Map<String, Object> result = new HashMap<>();
        result.put("success", addedCount > 0);
        result.put("count", addedCount);
        result.put("message", addedCount > 0 ? "成功添加" + addedCount + "件商品到购物车" : "未能添加商品到购物车，可能商品已下架或无库存");

        return Result.success(result);
    }
}